from flask import Blueprint,request,jsonify
from db import db1
from utils.acl import acl
from utils.rbac import rbac
import json
from utils.rs import rs
from utils.jwtc import myjwt
bp_user = Blueprint("user",__name__)

@bp_user.route('/login',methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    
    #用户账号密码
    sql = "select * from user where name='%s' and password='%s'"%(data['username'],data['password'])
    user = db1.find(sql)
    #判断用户名密码是否正确
    #生成token
    data = {'data':{"name":user['name'],"userid":user['id'],"is_admin":user['is_admin']}}
    token = myjwt.jwt_en(data)
    #获取用户页面权限、接口权限
    #页面列表，用户对应的资源acl
    if user['is_admin']:
        return jsonify({"code":200,'userid':user['id'],'username':user['name'],'token':token,'pagelist':[],'is_admin':user['is_admin']})
    
    pagelist = acl.get_page_reslist(user['id'])
    #url路由地址['/adduser','/content']
    interfacelist = acl.get_interface_reslist(user['id'])
    #用户对应的角色对应的资源
    key = 'interface'+str(user['id'])
    rs.insert_set(key,interfacelist)

    return jsonify({"code":200,'userid':user['id'],'username':user['name'],'token':token,'pagelist':pagelist,'is_admin':user['is_admin']})

# 用装饰器实现level为003在2021-10-01,2022-10-10时间段内内网对某个资源只有读取的权限
import functools
import datetime
def getPormition(func):
    @functools.wraps(func)
    def wrapper(*args,**kargs):
        #获取token
        token = request.headers['Token']
        #解析token
        payload = myjwt.jwt_de(token)
        uid = payload['data']['userid']
        #根据userid查询职务
        level = 'select 职务id from users where id='+uid
        values = rs.get_all_hash('rbac')
        if level == '003':
            #获取当前ip地址
            ip = request.remote_addr
            #获取当前日期
            time = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d')
            for k,v in values.items():
                key = str(k,encoding='utf8')
                if key == 'ip':
                    if ip != str(v,encoding='utf8'):
                        return 'ip限制'
                if key == 'time':
                    timev = eval(v)
                    if time<timev[0] or time >timev[1]:
                        return '时间限制'
            #读取判断
            if request.method not in ['GET','PUT']:
                return '只能访问get'
        return  func(*args,**kargs)
    return wrapper

@bp_user.route('/roleM',methods=['GET','POST','PUT','DELETE'])
def roleM():
    return 'sfsdf'

@bp_user.route('/test1')
def test1():
    list=[{1:2},{8:9},{4:2},{9:9}]

    # key='abac'
    # rs.insert_hash(key,'ip','127.0.0.1')
    # rs.insert_hash(key,'level','003')
    # rs.insert_hash(key,'time',"['2021-10-10','2021-12-10']")
    # values = rs.get_all_hash(key)
    # # print(type(values))
    # for (k,v) in values.items():
    #     if str(k,encoding='utf8') == 'time':
    #         print('sf')
    #         print(eval(v))
    return 'ok'




def getresdata(data):
   #把顶级拿出来放到列表中
    list=[]
    idlist=[]
    for i in data:
       id=i['pid']
       if id not in idlist:
           list.append({"id":id,'name':i['pname'],'son':[]})
           idlist.append(id)
   #遍历顶级列表，再遍历数据，把子类加到顶级列表中
    for j,value in enumerate(list):
        for i in data:
            if value['id'] == i['pid']:
                list[j]['son'].append({'id':i['id'],'name':i['name'],'url':i['url']})
    return list


@bp_user.route('/getResource')
def getResource():
    id = request.args.get('id')
    is_admin = request.args.get('is_admin')
 
    if int(is_admin) == 1:
        print("****")
        sql = "select r.name,r.url,r.id,pr.id as pid,pr.name as pname from resource as r  inner join resource as pr on pr.id=r.pid where r.type=1"
        res = db1.find_all(sql)
    else:
        print("!23423432!!@@@")
        res = acl.get_resourcelist(id,1)
        print(res)
    mes = getresdata(res)
    return jsonify({"list":mes})

@bp_user.route('/worklist')
def worklist():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({"code":200,'list':res})

#获取数据源接口
@bp_user.route('/getresourcedata',methods=['GET','POST'])
def getresourcedata():
    if request.method == 'GET':
        #从redis取，如果有直接返回
        values = rs.get_str('dataresouce')
        if values:
            list = eval(values)
        else:
            #如果没有查询
            sql = "select * from data_source"
            res = db1.find_all(sql)
            list = []
            if res:
                for i in res:
                    dict={'id':i['id'],'name':i['name']}
                    sql1 = "select id,name,type from %s"%(i['tablename'])
                    subres = db1.find_all(sql1)
                    dict['mes'] = subres
                    list.append(dict)
            #存入redis
            rs.set_str('dataresouce',json.dumps(list))
        return jsonify({"code":200,'list':list})
    else:
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "update workflow set params='%s' where id=%d"%(data['mes'],int(data['id']))
        db1.update(sql)
        return jsonify({"code":200})


@bp_user.route('/getworkf')
def getworkf():
    id = request.args.get('id')
    sql = "select * from workflow where id=%d"%(int(id))
    res = db1.find(sql)
    return jsonify({"code":200,'workf':res})

def getdeptdata(data):
    tree = {}
    list=[]
    for i in data:
        tree[i['id']] = i
    for j in data:
        pid = j['pid']
        if not pid:
            j['type']=1
            list.append(j)
        else:
            if 'children' not in tree[pid]:
                tree[pid]['children']=[]
            #查询此部门下所有员工
            sql = "select * from user where dept_id=%d"%(j['id'])
            res = db1.find_all(sql)
            userlist=[]
            if res:
                for u in res:
                    u['type'] = 3
                    userlist.append(u)
            j['children'] = userlist
            j['type']=2
            tree[pid]['children'].append(j)

    return list

@bp_user.route('/getcomanyuser')
def getcomanyuser():
    #获取所有公司及所有部门
    sql = "select * from dept"
    res = db1.find_all(sql)
    mes = getdeptdata(res)
    return jsonify({'code':200,'list':mes})
    #数据重组，查询员工
@bp_user.route('/taskm',methods=['POST','GET'])
def taskm():
    if request.method == "POST":
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form

        title = data['title']
        params = data['params']
        auditids = data['auditids']
        #添加任务
        sql = "insert into task(title,params,next_audit,status,nexta) values('%s','%s','%s',1,%d)"%(title,params,auditids,auditids[0])
        db1.update(sql)
    
        sql1 = "select id,title from task where title='%s'"%(title)
        task = db1.find(sql1)
        #把当前任务加到redis中，选用hash类型
        key='task%d'%(auditids[0])
        rs.insert_hash(key,task['id'],task['title'])
        return jsonify({"code":200})
    else:
        #通过任务id获取任务信息及对应的审批信息
       
        userid = request.args.get('userid')
        if userid:
            sql = "select * from task where userid=%d"%(int(userid))
            res = db1.find_all(sql)
            return jsonify({"code":200,'list':res})
            
        id = request.args.get('id')
        sql = "select * from task where id=%d"%(int(id))

        task = db1.find(sql)
        #此任务相关的审批记录
        sql1 = "select * from audit_record where taskid=%d"%(int(id))
        records = db1.find_all(sql1)
        task['audit_records'] = records
        return jsonify({"code":200,'task':task})

#待我审批
@bp_user.route('/mytaskaudit')
def mytaskaudit():
    id = request.args.get('id')
    #从redis中获取我的任务列表
    key='task%d'%(int(id))
    task = rs.get_all_hash(key)
    list=[]
    for k,v in task.items():
        id = str(k,encoding='utf8')
        title = str(v,encoding='utf8')
        list.append({'id':id,'title':title})

    return jsonify({"code":200,'list':list})

from utils.comm import get_data
@bp_user.route('/taskrecordM',methods=['POST'])
def taskrecordM():
    data = get_data()
    #写审批记录表
    time = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')
    try:
        sql = "insert into audit_record(taskid,userid,username,is_agree,reason,add_time) values(%d,%d,'%s',%d,'%s','%s')"%(int(data['taskid']),int(data['userid']),data['name'],int(data['agree']),data['reason'],time)
        db1.add(sql)
    except:
        return jsonify({"code":10010,'mes':'审批失败'})
   
    #判断是否同意
    tsql = "select * from task where id=%d"%(int(data['taskid']))
    task = db1.find(tsql)
    key='task%d'%(int(data['userid']))
    #清除当前redis中的信息
    rs.del_hash(key,int(data['taskid']))
    auditlist = json.loads(task['next_audit'])
    #是不是最后一个审批人
    index = auditlist.index(data['userid'])
    if data['agree'] == '1':
        try:
            #同意，查询任务，更新下一审批人，redis清除当前审批人，加入下一审批人，
            #任务表中更新任务状态，如果是最后一个审批人，查新成已经完成，其它审核中
            if index == len(auditlist)-1:
                sql1 = "update task set status=3,nexta=0 where id=%d"%(int(data['taskid']))
                db1.add(sql1)
            else:
                sql1 = "update task set status=2,nexta=%d where id=%d"%(auditlist[index+1],int(data['taskid']))
                db1.add(sql1)
                #添加redis
                newkey='task%d'%(int(auditlist[index+1]))
                #把下一审批人加入到redis
                rs.insert_hash(newkey,int(data['taskid']),task['title'])
            db1.commit()   
        except:
            db1.rollback()
            return jsonify({"code":10020,'mes':'失败'})
    else:
        #不同意，把redis中当前审批人清除，任务表中的下一审批人清空
        if index == 0:
            sql1 = "update task set status=1,nexta=0 where id=%d"%(int(data['taskid']))
            db1.update(sql1)
        else:
            sql1 = "update task set nexta=%d where id=%d"%(int(auditlist[index-1]),int(data['taskid']))
            db1.update(sql1)
            #添加redis
            newkey='task%d'%(int(auditlist[index-1]))
            #把下一审批人加入到redis
            rs.insert_hash(newkey,int(data['taskid']),task['title'])
    return jsonify({"code":200})

@bp_user.route('/testsql')
def testsql():
    try:
        sql1="insert into task(title) values('sfsf')"
        sql2 = "insert into user(name) values('234')"
        db1.add(sql1)
        db1.add(sql2)
        db1.commit()
        return 'sdfsdf'
    except:
        db1.rollback()
        return 'ok22'

    
@bp_user.route('/noticem',methods=['POST'])
def noticem():
    data = get_data()
    now = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')
    #添加通知表
    sql = "insert into notice(title,notice_type,content,type,level,ctime) values('%s',%d,'%s',%d,%d,'%s')"%(data['title'],int(data['notice_type']),data['content'],int(data['type']),int(data['level']),str(now))
    id = db1.update(sql)
    # 判断类型，如果为3写入notice_record
    if int(data['type']) ==3:
        list = data['userids']
        for i in list:
            sql1="insert into notice_record(notice_id,userid,ctime) values(%d,%d,'%s')"%(int(id),int(i),now)
            db1.update(sql1)
    return jsonify({"code":200})

@bp_user.route('/getnotice')
def getnotice():
    userid = int(request.args.get('id'))
    sql = "select id,title,ctime,level,type from notice where type=1 or id in(select notice_id from notice_record  where userid=%d)  order by ctime desc,level asc"%(int(userid))
    res = db1.find_all(sql)
    mes=[]

    for i in res:
        i['status'] = 0
        #消息发给所有人
        if int(i['type']) == 1:
            #点击进入详情页，在详情页里更新redis set
            key = 'notice'+str(i['id'])
            print(key)
            #此条消息的已读列表
            list = rs.find_set(key)
            if list:
                if str(userid) in list:
                    i['status'] = 1
        if int(i['type']) == 3:
            sql4 = "select status from notice_record where notice_id=%d and userid=%d"%(i['id'],int(userid))
            res4 = db1.find(sql4)
            if res4 and int(res4['status']) == 1:
                i['status'] = 1
        mes.append(i)
    return jsonify({"code":200,'list':mes})

       
@bp_user.route('/updatenotice',methods=['POST'])
def updatenotice():
    #获取信息
    data = get_data()
    #查看消息类型，如果消息类型为1，向redis中添加数据
    sql = "select * from notice where id=%d"%(int(data['noticeid']))
    notice = db1.find(sql)
    if int(notice['type']) == 1:
        key = 'notice'+str(notice['id'])
        rs.insert_set(key,int(data['userid']))
    #如果消息为3更新数据库
    if int(notice['type']) == 3:
        sql1 = "update notice_record set status=1 where notice_id=%d and userid=%d"%(int(data['noticeid']),int(data['userid']))
        db1.update(sql1)
    return jsonify({"code":200})

from tasks import celery
import time
@bp_user.route('/customer_reg',methods=['POST'])
@celery.task()
def customer_reg():
    data = get_data()
    now = int(time.time())
    sql = "insert into customer(name,company_name,manager_id,refromid,addtime) values('%s','%s',%d,%d,%d)"%(data['name'],data['company'],int(data['manager_id']),int(data['refromid']),now)
    db1.update(sql)
    return jsonify({"code":200})

@bp_user.route('/managelist')
def managelist():
    sql = "select * from customer_manager"
    res = db1.find_all(sql)
    return jsonify({"code":200,'list':res})

@bp_user.route('/resourcelist')
def resourcelist():
    sql = "select * from reg_form"
    print(sql)
    res = db1.find_all(sql)
    return jsonify({"code":200,'list':res})




    




